package com.yxhl.zoume.core.officialcar.fragment;


import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.yxhl.protobuf.MpvModel;
import com.yxhl.protobuf.OrderBizType;
import com.yxhl.protobuf.RentalTime;
import com.yxhl.zoume.R;
import com.yxhl.zoume.ZouMeApplication;
import com.yxhl.zoume.common.info.ToolbarType;
import com.yxhl.zoume.common.ui.fragment.BaseFragment;
import com.yxhl.zoume.core.specialcar.model.CarLocationMapEntrance;
import com.yxhl.zoume.core.officialcar.model.OfficialCarRentTimePicker;
import com.yxhl.zoume.core.officialcar.model.OfficialCarZMTimePicker;
import com.yxhl.zoume.core.officialcar.presenter.CreateOfficialCarOrderPresenter;
import com.yxhl.zoume.core.officialcar.presenter.InitializeOfficialCarPresenter;
import com.yxhl.zoume.core.officialcar.presenter.RentHourlyTimePickerPresenter;
import com.yxhl.zoume.core.officialcar.presenter.RentHourlyTimeQueryPresenter;
import com.yxhl.zoume.core.officialcar.activity.OfficialCarContainerActivity;
import com.yxhl.zoume.core.car.model.CarOtherPassengerEvent;
import com.yxhl.zoume.core.officialcar.view.CreateOfficialCarOrderView;
import com.yxhl.zoume.core.car.view.common.GetRentCarTimeView;
import com.yxhl.zoume.core.officialcar.view.RentHourlyQueryView;
import com.yxhl.zoume.core.car.view.common.VehicleShowView;
import com.yxhl.zoume.core.func.map.ui.event.SelectedPOIEvent;
import com.yxhl.zoume.core.func.timepicker.presenter.ZMTimePickerPresenter;
import com.yxhl.zoume.core.func.timepicker.view.ZMTimePickerView;
import com.yxhl.zoume.data.http.model.account.ZMAccount;
import com.yxhl.zoume.di.component.car.DaggerOfficialCarComponent;
import com.yxhl.zoume.di.module.ActivityModule;
import com.yxhl.zoume.utils.AccountUtils;
import com.yxhl.zoume.utils.LOG;
import com.yxhl.zoume.utils.PromptUtils;
import com.yxhl.zoume.utils.ZMDialog;
import com.yxhl.zoume.utils.permission.PermissionHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.BindViews;
import butterknife.OnClick;
import rx.Subscription;
import rx.functions.Action1;

/**
 * created by sugarya 16/08/15
 * 公务车 分时租车
 */
public class RentHourlyOfficialCarFragment extends BaseFragment implements ZMTimePickerView, VehicleShowView
        , GetRentCarTimeView, CreateOfficialCarOrderView, RentHourlyQueryView {

    private static final String TAG = "RentHourlyOfficialCarFrag";


    //widgets
    @BindView(R.id.tv_include_call_car_content)
    TextView mCallCarContentTv;

    @BindView(R.id.tv_include_get_in_location)
    TextView mGetInLocationTv;

    @BindView(R.id.tv_include_reservation_time)
    TextView mReservationTimeTv;

    @BindView(R.id.tv_include_rent_car_time)
    TextView mRentCarTimeTv;

    @BindView(R.id.tv_fragment_rent_hourly_official_car_description)
    TextView mRentHourlyDescriptionTv;

    @BindView(R.id.btn_fragment_rent_hourly_submit)
    Button mCentHourlySubmitBtn;

    @BindViews({R.id.iv_fragment_rent_hourly_official_car_previous, R.id.iv_fragment_rent_hourly_official_car_next})
    List<ImageView> mArrowIvs;

    @BindView(R.id.hsv_fragment_rent_hourly_official_car)
    HorizontalScrollView mVehicleHsv;

    @BindView(R.id.rg_fragment_rent_hourly_container)
    RadioGroup mRentHourlyContainerRg;

    //arguments
    @Inject
    ZMTimePickerPresenter mZMTimePickerPresenter;

    @Inject
    RentHourlyTimePickerPresenter mRentHourlyTimePickerPresenter;

    @Inject
    InitializeOfficialCarPresenter mInitializeOfficialCarPresenter;

    @Inject
    CreateOfficialCarOrderPresenter mCreateOfficialCarOrderPresenter;
    @Inject
    RentHourlyTimeQueryPresenter mRentHourlyTimeQueryPresenter;

    private Subscription mGetInSubscription;
    private Subscription mCallCarForOthersSubscription;

    private String mAccountName;
    /**
     * 租车时间选择器,选项作为key,对应的距离/时长描述数据作为value
     */
    private HashMap<String, String> mRentCarDescriptionMap;

    private MaterialDialog loadingDialog;


    public RentHourlyOfficialCarFragment() {
        // Required empty public constructor
    }

    public static RentHourlyOfficialCarFragment newInstance() {
        RentHourlyOfficialCarFragment fragment = new RentHourlyOfficialCarFragment();
        return fragment;
    }

    /**
     * 替他人叫车回调
     */
    private void onCallCarForOthersRxBusEvent() {
        mCallCarForOthersSubscription = toSubscription(CarOtherPassengerEvent.class,
                new Action1<CarOtherPassengerEvent>() {
                    @Override
                    public void call(CarOtherPassengerEvent carOtherPassengerEvent) {

                        handleCarOtherPassengerEvent(carOtherPassengerEvent, mCallCarContentTv, mAccountName);

                        //数据检验
                        checkCompleteData();

                        //取消订阅关系
                        if (mCallCarForOthersSubscription != null && !mCallCarForOthersSubscription.isUnsubscribed()) {
                            mCallCarForOthersSubscription.unsubscribe();
                        }
                    }
                },
                new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LOG.e(TAG, "throwable=" + throwable.toString());
                        onCallCarForOthersRxBusEvent();
                    }
                }
        );

        //替他人叫车
        getSubscription().add(mCallCarForOthersSubscription);

    }


    /**
     * 上车
     */
    private void onGetInRxBusEvent() {
        mGetInSubscription = toSubscription(SelectedPOIEvent.class,
                new Action1<SelectedPOIEvent>() {
                    @Override
                    public void call(SelectedPOIEvent selectedPOIEvent) {
                        //显示分时租车页
                        ((OfficialCarContainerActivity) mActivity).displayOneFragment(
                                OfficialCarContainerActivity.FRAGMENT_RENT_HOURLY,
                                CarLocationMapEntrance.DEFAULT);
                        //处理选中数据
                        handleGetInSelectedPOIEvent(selectedPOIEvent, mGetInLocationTv);

                        //数据完整性检查
                        checkCompleteData();

                        //取消订阅关系
                        if (mGetInSubscription != null && !mGetInSubscription.isUnsubscribed()) {
                            mGetInSubscription.unsubscribe();
                        }
                    }
                },
                new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LOG.e(TAG, "throwable=" + throwable.toString());
                        onCallCarForOthersRxBusEvent();
                    }
                }
        );
        //选择上车地点
        getSubscription().add(mGetInSubscription);
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        mZMTimePickerPresenter.attachView(this);
        mRentHourlyTimePickerPresenter.attachView(this);
        mInitializeOfficialCarPresenter.attachView(this);
        mCreateOfficialCarOrderPresenter.attachView(this);
        mRentHourlyTimeQueryPresenter.attachView(this);
        initializeListener();
        initializeStatusData();
        return view;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            setupToolBar();
        }
    }

    /**
     * 初始化数据
     */
    private void initializeStatusData() {
        initializeMobileNumberData();
        mInitializeOfficialCarPresenter.queryOfficialCarDisplayData(OrderBizType.OFFICIAL_BUS_TIME);

    }

    private void initializeListener() {
        mRentHourlyContainerRg.setOnCheckedChangeListener(new VehicleOnCheckedChangeLister());
    }

    /**
     * /**
     * 默认显示用户手机号
     */
    private void initializeMobileNumberData() {
        ZMAccount account = AccountUtils.getInstance(mActivity).getAccount();
        if (account != null) {
            mAccountName = account.getAccountName();
            if (!TextUtils.isEmpty(mAccountName)) {
                if (mCallCarContentTv != null) {
                    mCallCarContentTv.setText(mAccountName);
                }
            }
        }
    }


    /**
     * 为他人叫车 监听
     */
    @OnClick(R.id.tv_include_call_others_right)
    void onCallCarForOthersClick() {
        onCallCarForOthersRxBusEvent();
        ZouMeApplication.application.getAppComponent().navigator().navigateToCallCarForOthersActivity(mActivity);
    }

    /**
     * 上车 监听
     */
    @OnClick(R.id.tv_include_get_in_location)
    void onGetInLocationClick() {
        onGetInRxBusEvent();

        if (PermissionHelper.checkLocationPermission(mActivity)) {
            ((OfficialCarContainerActivity) mActivity).displayOneFragment(
                    OfficialCarContainerActivity.FRAGMENT_CAR_LOCATION_MAP,
                    CarLocationMapEntrance.OFFICIAL_CAR_RENT_HOURLY_GET_IN);
        } else {
            PermissionHelper.takeLocationPermission(
                    this,
                    PermissionHelper.REQUEST_CODE_OFFICIAL_CAR_RENT_HOURLY_GET_IN_LOCATION);
        }
    }

    /**
     * 出行时间 监听
     */
    @OnClick(R.id.tv_include_reservation_time)
    void onReservationClick() {
        mZMTimePickerPresenter.showZMTimePicker(OfficialCarZMTimePicker.class);
    }

    /**
     * 租车时间 监听
     */
    @OnClick(R.id.tv_include_rent_car_time)
    void onRentCarTimeClick() {
        mRentHourlyTimePickerPresenter.showRentHourlyTimePicker(OfficialCarRentTimePicker.class);
    }

    /**
     * 上一个
     */
    @OnClick(R.id.iv_fragment_rent_hourly_official_car_previous)
    void onPreviousVehicleClick() {
        mVehicleHsv.smoothScrollBy(-mInitializeOfficialCarPresenter.getVehicleTotalDisplayWith(), 0);
    }

    /**
     * 下一个
     */
    @OnClick(R.id.iv_fragment_rent_hourly_official_car_next)
    void onNextVehicleClick() {
        mVehicleHsv.smoothScrollBy(mInitializeOfficialCarPresenter.getVehicleTotalDisplayWith(), 0);
    }

    /**
     * 下单
     */
    @OnClick(R.id.btn_fragment_rent_hourly_submit)
    void onCreateRentHourlyOrderClick() {
        mCreateOfficialCarOrderPresenter.createOfficialCarOrder(OrderBizType.OFFICIAL_BUS_TIME);
    }

    //时间选择器选择回调
    @Override
    public void renderZMTimePickerOptionSelectResult(String zmTimePickerSimpleName, String options1, String options2, String options3) {
        if (OfficialCarZMTimePicker.class.getSimpleName().equals(zmTimePickerSimpleName)) {
            mCreateOfficialCarOrderPresenter.handleZMTimePickerSelectResult(options1, options2, options3);
            mReservationTimeTv.setText(options1 + " " + options2 + " " + options3);

        } else if (OfficialCarRentTimePicker.class.getSimpleName().equals(zmTimePickerSimpleName)) {
            mRentCarTimeTv.setText(options1);
            mRentHourlyTimeQueryPresenter.setPartTime(Integer.valueOf(handleRentHourlyTimePickerSelectResult(options1)));
            checkCompleteData();
            mCreateOfficialCarOrderPresenter.handleRentHourlyTimePickerSelectResult(options1);

            if (mRentCarDescriptionMap != null) {
                //      mRentHourlyDescriptionTv.setText(mRentCarDescriptionMap.get(options1));
            }
        }
        checkCompleteData();
    }

    //查询车型回调
    @Override
    public void renderVehicleModelDataOnSuccess(List<MpvModel> vehicleModelsList) {
        mInitializeOfficialCarPresenter.initializeArrowShow(mArrowIvs);
        mInitializeOfficialCarPresenter.initializeVehicleShowByOnline(mRentHourlyContainerRg);
    }

    @Override
    public void renderVehicleModelDataOnFailure(String msg) {
        PromptUtils.showShort(mActivity, msg);
    }

    @Override
    public void renderVehicleModeDataOnError(String errorMsg) {
        PromptUtils.showShort(mActivity, getString(R.string.net_error));
    }

    //租车时长
    @Override
    public void renderRentCarTimeOnSuccess(List<RentalTime> rentalTimesList) {
        mRentCarDescriptionMap = new HashMap<>();
        ArrayList<String> optional1List = new ArrayList<>();

        for (RentalTime rentalTime : rentalTimesList) {
            String rentalTimeDesc = rentalTime.getDesc();
            String partTime = rentalTime.getPartTime();
            String rentalKey = "租车" + partTime + "小时";
            if (rentalTimeDesc != null) {
                optional1List.add(rentalKey);
            }


            mRentCarDescriptionMap.put(rentalKey, rentalTimeDesc);
        }

        mRentHourlyTimePickerPresenter.setOptions1List(optional1List);

    }

    // 下单回调
    @Override
    public void renderOfficialCarOrderOnSuccess(String orderId) {
        getAppComponent().navigator().navigateToOfficialCarScheduleActivity(mActivity, orderId);
    }

    @Override
    public void renderOfficialCarOrderOnFailure(String failureMsg) {
        PromptUtils.showShort(getContext(), failureMsg);
        showWaitingDialog(false);
    }

    @Override
    public void renderOfficialCarOrderOnError(String errorMsg) {
        PromptUtils.showShort(getContext(), getString(R.string.net_error));
    }

    @Override
    public void showWaitingDialog(boolean needShow) {
        if (needShow) {
            loadingDialog = ZMDialog.getLoadingDialog(mActivity);
        } else {
            if (loadingDialog != null) {
                loadingDialog.dismiss();
            }
        }
    }

    /**
     * 下单数据 完整性检查
     */
    private void checkCompleteData() {
        String mobileNumber = mCallCarContentTv.getText().toString();
        String getInLocation = mGetInLocationTv.getText().toString();
        String reservationTime = mReservationTimeTv.getText().toString();
        String rentCarTime = mRentCarTimeTv.getText().toString();

        if (TextUtils.isEmpty(getInLocation)) {
            return;
        }

        if (TextUtils.isEmpty(rentCarTime)) {
            return;
        }

        boolean selected = mRentHourlyContainerRg.getCheckedRadioButtonId() > -1;
        if (mRentHourlyTimeQueryPresenter != null && selected &&
                (!TextUtils.isEmpty(rentCarTime))) {
            mRentHourlyTimeQueryPresenter.queryPriceAndDistance(OrderBizType.OFFICIAL_BUS_TIME);
        }

        if (TextUtils.isEmpty(mobileNumber)) {
            return;
        }

        if (TextUtils.isEmpty(reservationTime)) {
            return;
        }

        mCentHourlySubmitBtn.setEnabled(true);
    }

    /**
     * 处理事件
     *
     * @param carOtherPassengerEvent
     * @param callCarContentTv
     * @param accountName
     */
    private void handleCarOtherPassengerEvent(CarOtherPassengerEvent carOtherPassengerEvent, TextView callCarContentTv, String accountName) {
        String otherMobile = carOtherPassengerEvent.getPassengerMobile();
        boolean needSendMsg = carOtherPassengerEvent.isNeedSendMsg();

        if (!TextUtils.isEmpty(otherMobile)) {
            if (callCarContentTv != null) {
                callCarContentTv.setText(otherMobile);
            }
            mCreateOfficialCarOrderPresenter.setOtherMobile(otherMobile);
            mCreateOfficialCarOrderPresenter.setNeedSendMsg(needSendMsg);
            if (!otherMobile.equalsIgnoreCase(accountName)) {
                mCreateOfficialCarOrderPresenter.setNeedCallCarForOthers(true);
            } else {
                mCreateOfficialCarOrderPresenter.setNeedCallCarForOthers(false);
            }
        }
    }

    /**
     * 处理上车 回调事件
     *
     * @param selectedPOIEvent
     * @param getInLocationTv
     */
    private void handleGetInSelectedPOIEvent(SelectedPOIEvent selectedPOIEvent, TextView getInLocationTv) {
        PoiItem poiItem = selectedPOIEvent.getPoiItem();
        if (poiItem != null) {
            String title = poiItem.getTitle();
            getInLocationTv.setText(title);

            //查询距离和价格 准备数据
            LatLonPoint latLonPoint = poiItem.getLatLonPoint();
            if (latLonPoint != null) {
                double latitude = latLonPoint.getLatitude();
                double longitude = latLonPoint.getLongitude();
                mRentHourlyTimeQueryPresenter.setLat(String.valueOf(latitude))
                        .setLng(String.valueOf(longitude));

                mCreateOfficialCarOrderPresenter.setStartLocation(title);
                mCreateOfficialCarOrderPresenter.setLat(String.valueOf(latitude));
                mCreateOfficialCarOrderPresenter.setLng(String.valueOf(longitude));
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults.length > 0) {
            switch (requestCode) {
                case PermissionHelper.REQUEST_CODE_OFFICIAL_CAR_RENT_HOURLY_GET_IN_LOCATION:
                    if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        ((OfficialCarContainerActivity) mActivity).displayOneFragment(
                                OfficialCarContainerActivity.FRAGMENT_CAR_LOCATION_MAP,
                                CarLocationMapEntrance.OFFICIAL_CAR_RENT_HOURLY_GET_IN);
                    } else {
                        PromptUtils.showShort(mActivity, getString(R.string.permission_location_alert_message));
                    }
                    break;
            }
        }
    }

    @Override
    public void renderQueryPriceAndDistanceOnSuccess(String description) {
        if (!TextUtils.isEmpty(description)) {
            mRentHourlyDescriptionTv.setText(description);
        }
    }

    @Override
    public void renderQueryPriceAndDistanceOnFailure(String failureMsg) {
        PromptUtils.showShort(mActivity, failureMsg);
    }

    @Override
    public void renderQueryPriceAndDistanceOnError(String errorMsg) {
        PromptUtils.showShort(mActivity, getString(R.string.net_error));
    }

    @Override
    protected void initializeInjector() {
        DaggerOfficialCarComponent
                .builder()
                .appComponent(getAppComponent())
                .activityModule(new ActivityModule(mActivity))
                .build()
                .inject(this);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_rent_hourly_official_car;
    }

    @Override
    protected void setupToolBar() {
        if (mActivity instanceof OfficialCarContainerActivity) {
            OfficialCarContainerActivity containerActivity = ((OfficialCarContainerActivity) mActivity);
            containerActivity.changeToolbarInto(ToolbarType.RENT_HOURLY);
        }
    }

    public String handleRentHourlyTimePickerSelectResult(String options1) {
        Pattern pattern = Pattern.compile("\\d+");
        Matcher matcher = pattern.matcher(options1);
        if (matcher.find()) {
            return matcher.group();
        } else {
            return "4";
        }
    }

    /**
     * 车辆类型选择
     */
    class VehicleOnCheckedChangeLister implements RadioGroup.OnCheckedChangeListener {

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            RadioButton checkedRb = (RadioButton) group.findViewById(checkedId);
            if (checkedRb != null) {
                String vehicleType = (String) checkedRb.getTag();
                mCreateOfficialCarOrderPresenter.setVehicleType(vehicleType);
                mRentHourlyTimeQueryPresenter.setVehicleType(vehicleType);
                checkCompleteData();
            }
        }
    }
}
